package com.sherry.uitils;

import com.sherry.uitils.dbutils.DBConnectionInfo;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * Created by swl on 2021/5/31.
 */
public class ConfigUtil {

    private static ResourceBundle bundle;
    private static Logger logger = Logger.getLogger("ConfigUtil");

    public static String getHostConfig() {
        String url = "";
        try {
            bundle = ResourceBundle.getBundle("config", Locale.CHINA);
        } catch (Exception e) {
            logger.error("配置文件不存在，请检查");
            e.printStackTrace();
        }
        try {
            url = bundle.getString("baseURL");
        } catch (Exception e) {
            logger.error("baseURL配置可能不对，请检查");
            e.printStackTrace();
        }
        return url;
    }

    public static Map<String, DBConnectionInfo> getDbConfigInfo() {
        String url = getHostConfig();
        String fileName = "db_test";
        if (url.contains("fws")) {
            fileName = "db_fws";
        }
        if (url.contains("lpt")) {
            fileName = "db_lpt";
        }

        Map<String, DBConnectionInfo> dbConnectionInfoMap = new HashMap<String, DBConnectionInfo>();

        try {
            bundle = ResourceBundle.getBundle(fileName, Locale.CHINA);
        } catch (Exception e) {
            logger.error("配置文件不存在，请检查");
            e.printStackTrace();
        }

        int count = Integer.valueOf(bundle.getString("DBConnectionCounts")) == null ? 20 : Integer.valueOf(bundle.getString("DBConnectionCounts"));
        for (int index = 1; index <= count; index++) {
            String dbs = bundle.getString("dbServers_" + index);
            if (dbs == null) {
                continue;
            }

            String userName;
            try {
                userName = bundle.getString("username_"+index);
            }catch (Exception e){
                userName = bundle.getString("username");
            }

            String password;
            try {
                password = bundle.getString("password_"+index);
            }catch (Exception e){
                password = bundle.getString("password");
            }

            String[] dbservers = bundle.getString("dbServers_" + index).split(";");
            for (String dbserver : dbservers) {
                DBConnectionInfo dbConnectionInfo = new DBConnectionInfo();
                dbConnectionInfo.setDbServerName(dbserver);
                dbConnectionInfo.setDbUrl(bundle.getString("dburl_" + index));
                dbConnectionInfo.setUserName(userName);
                dbConnectionInfo.setPassword(password);
                dbConnectionInfoMap.put(dbserver, dbConnectionInfo);
            }
        }
        return dbConnectionInfoMap;
    }
}
